package com.wuhongyu.service.impl;

import com.wuhongyu.base.BaseServiceImpl;
import com.wuhongyu.common.MyCommon;
import com.wuhongyu.entity.Dictionary;
import com.wuhongyu.repository.DictionaryDao;
import com.wuhongyu.service.DictionaryService;
import com.wuhongyu.util.MyUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service("dictionaryService")
public class DictionaryServiceImpl extends BaseServiceImpl<Dictionary> implements DictionaryService {

    private DictionaryDao dictionaryDao;

    @Resource
    public void setDao(DictionaryDao dictionaryDao) {
        super.setBaseDao(dictionaryDao);
        this.dictionaryDao = dictionaryDao;
    }

    @Override
    public Page<Dictionary> findAll(Dictionary dictionary, Integer number) {
        Specification<Dictionary> spec = (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (MyUtil.notEmpty(dictionary.getType()))
                list.add(cb.like(root.get("type"), "%" + dictionary.getType() + "%"));
            if (MyUtil.notEmpty(dictionary.getItems()))
                list.add(cb.like(root.get("items"), "%" + dictionary.getItems() + "%"));
            if (MyUtil.notEmpty(dictionary.getValue()))
                list.add(cb.like(root.get("value"), "%" + dictionary.getValue() + "%"));
            return cb.and(list.toArray(new Predicate[list.size()]));
        };
        return dictionaryDao.findAll(spec, new PageRequest(MyUtil.getCurrentPage(number), MyCommon.PAGESIZE));
    }

    @Override
    public void save(Dictionary dictionary) {
        if (dictionary.getStatus() == null) {
            dictionary.setStatus(0);
        }
        dictionaryDao.saveAndFlush(dictionary);
    }

    @Override
    public List<Dictionary> findByType(String type) {
        return dictionaryDao.findByTypeEquals(type);
    }
}